package com.example.weibo_app.controller;

import com.example.weibo_app.common.utils.AjaxResult;
import com.example.weibo_app.domain.Banner;
import com.example.weibo_app.service.BannerService;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.multipart.MultipartFile;

import javax.validation.constraints.Min;
import java.io.File;
import java.io.IOException;
import java.util.UUID;

@RestController
@Api(tags = "轮播图管理")
public class BannerController {
    @Autowired
    private BannerService bannerService;

    // 添加新的 Banner
    @PostMapping("/banners")
    @ApiOperation(value = "添加新的Banner")
    public AjaxResult addBanner(String title, @RequestPart MultipartFile file) throws IOException {
        //判断文件是否存在
        if (file == null) {
            return AjaxResult.error("必须上传至少一张图片");
        }
        //创建基本路径（文件的基本路径）
        String basePath = System.getProperty("user.dir") + "/uploads/";
        File uploadDir = new File(basePath); // 创建文件夹
        if (!uploadDir.exists()) { // 如果文件目录不存在
            uploadDir.mkdirs(); // 创建目录
        }
        //使用UUID保证文件名唯一
        String src = UUID.randomUUID().toString().replace("-", "") + file.getOriginalFilename();
        File dest = new File(basePath + src); // 创建文件
        file.transferTo(dest); //保存到本地
        Banner banner = new Banner();
        banner.setImage_Path(src);
        banner.setTitle(title);
        banner.setStatus(1);
        return AjaxResult.success(bannerService.addBanner(banner));
    }

    // 更新 Banner 状态
    @DeleteMapping("/banners/{id}")
    @ApiOperation(value = "更新Banner 状态")
    public AjaxResult removeBanner(@PathVariable @Min(1) int id) {
        return AjaxResult.success(bannerService.updateBanner(id));
    }


    // 获取所有 Banner
    @GetMapping("/bannersList")
    @ApiOperation(value = "获取所有Banner")
    public AjaxResult getAllBanners() {
        return AjaxResult.success(bannerService.getAllBanners());
    }
}
